{% for item in inlineScripts %}
  {% set inlineScript %}
    {% includeRaw item %}
  {% endset %}
  <script>{{ inlineScript | minifyJs | cspHash | safe }}</script>
{% endfor %}


{# Sourced scripts cannot be authorized by a CSP hash individually, so we need
to use an inline script loader for any sourced scripts. #}
{# This works because the CSP includes the 'strict-dynamic' keyword, allowing
the children of an authorized script to run. #}
{% include 'partials/load-script-func.njk' %}
{% set loadScripts %}
  loadScript('{{ helpers.hashForProd('/js/app.js') }}', 'module');

  {# Add a facility for pages to declare an array of script paths. #}
  {# If no scripts are declared we will use the default page script. #}
  {# default.js loads the basic set of custom elements that all pages need. #}

  {# Dispatch event to notify that all pageScripts got loaded. #}
  {% if pageScripts %}
    let pageScripts = {{ pageScripts | dump | safe }};
    document.addEventListener('scriptLoaded', (e) => {
      const source = e.detail.url.split('?')[0]
      const index = pageScripts.indexOf(source);
      if (index > -1) {
        pageScripts.splice(index, 1);
      }
      if (pageScripts.length === 0) {
        document.dispatchEvent(new CustomEvent('pageScriptsLoaded'));
      }
    })
  {% endif %}
  {% for item in pageScripts %}
    loadScript('{{ helpers.hashForProd(item) }}', 'module');
  {% else %}
    loadScript('{{ helpers.hashForProd('/js/default.js') }}', 'module');
  {% endfor %}

  {% for item in externalScripts %}
    loadScript('{{item}}', null);
  {% endfor %}
{% endset %}
<script>{{ loadScripts | minifyJs | cspHash | safe }}</script>

